
installfile=mongodb-linux-x86_64-rhel62-3.4.7.tgz
prefix=/opt/local/mongodb
datapath=$prefix/data
logpath=$prefix/mongo.log
pidpath=$prefix/mongo.pid
confpath=$prefix/conf
conffile=$confpath/mongo.conf

port=27017
admin=admin
adminpass=admin@2016
admindb=admin
appdb=appdb
appuser=appuser
appuserpass=appuser@2016

function makefolder(){
  folder=$1
  if [ ! -d $folder ]; then
    echo "make $folder"
    mkdir -p $folder
  fi
}

tar -xzvf $installfile

if [ -d $prefix ]; then
  echo "clear $prefix"
  rm -r $prefix
fi

mv ${installfile//.tgz//} $prefix

makefolder $datapath
makefolder $confpath

conf_str='
storage:
    dbPath: "{datapath}"
    engine: wiredTiger
    directoryPerDB: true
    journal:
        enabled: true
systemLog:
    destination: file
    path: "{logpath}"
    logAppend: true
#   timeStampFormat: iso8601-utc
operationProfiling:
   slowOpThresholdMs: 10000
replication:
    oplogSizeMB: 700
processManagement:
    fork: true
    pidFilePath: "{pidpath}"
net:
    port: {port}
    http:
      enabled: false
    unixDomainSocket:
      enabled : false
'

echo "generate config file $conffile"

echo "$conf_str" > $conffile
sed -i "s/{datapath}/${datapath//\//\/}/g" $conffile
sed -i "s/{logpath}/${logpath//\//\/}/g" $conffile
sed -i "s/{pidpath}/${pidpath//\//\/}/g" $conffile
sed -i "s/{port}/${port//\//\/}/g" $conffile


echo "generate shell scripts.."
sh_start=$prefix/start.sh
sh_stop=$prefix/stop.sh
sh_test=$prefix/test.sh
sh_log=$prefix/showlog.sh
sh_conn=$prefix/conn.sh
sh_stat=$prefix/stat.sh

echo "$prefix/bin/mongod -f $conffile -auth" > $sh_start
echo "kill -2 \`cat $pidpath\`
rm $pidpath"  > $sh_stop
echo "netstat -nlp |grep $port" > $sh_test
echo "tail -n200 -f $logpath" > $sh_log
echo "$prefix/bin/mongo --port $port -u $admin -p $adminpass --authenticationDatabase=$admindb" > $sh_conn
echo "$prefix/bin/mongostat --port $port  -u $admin -p $adminpass --authenticationDatabase=$admindb --discover -n 300 3" > $sh_stat

chmod +x $sh_start
chmod +x $sh_stop
chmod +x $sh_test
chmod +x $sh_log
chmod +x $sh_conn
chmod +x $sh_stat

echo "generate init.js"
script_init=$prefix/script/init.js
mkdir -p $prefix/script

echo "
conn = new Mongo();
db = conn.getDB('$admindb');
db.createUser({user:'$admin',pwd:'$adminpass',roles:[{role:'clusterAdmin',db:'$admindb'},{role:'userAdminAnyDatabase',db:'$admindb'},{role:'readWriteAnyDatabase',db:'$admindb'}]});

db = conn.getDB('$appdb');
db.createUser({user:'$appuser',pwd:'$appuserpass',roles:[{role:'dbOwner',db:'$appdb'}]})
" > $script_init

echo "start mongod with no auth"
$prefix/bin/mongod -f $conffile

echo "init user data.."
$prefix/bin/mongo --port $port $script_init

echo "turnoff mongo and restart.."
kill -2 `cat $pidpath`

sleep 1
sh $sh_start
echo "mongo start. use port=$port"
